﻿using System;
using System.Media;
using Calendar.Properties;

namespace Calendar.Domain
{
    public delegate void UpdateHandler();
    public delegate void ChangeStateHandler();

    public class Pomodoro
    {
        public UpdateHandler Update = null;
        public ChangeStateHandler ChangeState = null;
        TimeAllocation _timeAllocation;
        PomodoroState _currentState;
        double _slotAmount;

        public Pomodoro()
        {
            _timeAllocation = new TimeAllocation();
            ChangeState += ChangePomodoroState;
            _slotAmount = 0;
        }

        public void SetTimeAllocation(int timeSlot, int breakTime)
        {
            _timeAllocation.TimeSlot = timeSlot;
            _timeAllocation.BreakTime = breakTime;
        }

        public void StartPomodoro()
        {
            _currentState = new PomodoroWork(_timeAllocation);
            SetEvent();
            _currentState.StartTimer();
        }

        private void SetEvent()
        {
            _currentState.Update += ProcessUpdate;
            _currentState.ChangeState += ChangePomodoroState;
        }

        public void ChangePomodoroState()
        {
            Alarm();
            _slotAmount += 0.5;
            _currentState = _currentState.NextPomodoroState;
            SetEvent();
            _currentState.StartTimer();
        }

        private void Alarm()
        {
            SoundPlayer soundPlayer = new SoundPlayer(Resources.alarm);
            soundPlayer.Play();
        }

        public void StopPomodoro()
        {
            _currentState.StopTimer();
        }

        public void ProcessUpdate()
        {
            Update.Invoke();
        }

        public string TimerLabelText
        {
            get
            {
                return _currentState.TimeLabelText + "\n累計 " + Math.Ceiling(_slotAmount) + " 個工作回合";
            }
        }

        public int PomodoroProgressBarValue
        {
            get
            {
                return _currentState.PomodoroProgressBarValue;
            }
        }
    }
}
